import React from 'react';
import './userlist.less';
import { Breadcrumb, Icon, Button, Table, Modal, Input, Select, Pagination, message } from 'antd';
import $ from 'jquery';
import Config from '../common/config';

const config = new Config();
const Option = Select.Option;
const InputGroup = Input.Group;
const token = sessionStorage.getItem('token')

export default class UserList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            usersList: [],// 会员列表
            usersCount: 0,//会员数
            pagesize: 10,// 每页显示的页数
            pageindex: 1,// 当前页
            Inkey: '',// 关键字
            sex: '请选择',//性别
            userState: '请选择',//状态
            operationType: "解封",
            visible: false, //解封对话框
            user: undefined, //操作的会员数据 
            userVisible: false, //会员信息对话框  
            userData: {}, //查看的会员信息     
            addressList: [], //会员的地址列表 
        }
    }

    componentDidMount() {
        //获取会员列表
        this.getUsersList();
    }
    //获取会员列表
    getUsersList() {
        $.ajax({
            url: `${config.JuseMember}/userManage/list`,
            type: "get",
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            data: {
                pageSize: this.state.pagesize,
                page: this.state.pageindex,
                inkey: this.state.Inkey,//关键字
                sex: this.state.sex == "请选择" ? '' : this.state.sex,//性别
                userState: this.state.userState == "请选择" ? '' : this.state.userState,//状态
            },
            success: res => {
                console.log('会员列表', res)
                if (res.code === 200) {
                    const usersList = res.data.rows;
                    if (usersList.length > 0) {
                        usersList.forEach((ele, i) => {
                            ele.index = i + 1;
                        });
                    }
                    this.setState({
                        usersList: usersList,
                        usersCount: res.data.count,
                    });
                } else {
                    message.config({ top: 80, });
                    message.error('获取会员列表失败，请返回重新操作', 2);
                }
            }
        });
    }
    //解封/封号操作
    userOperation(record) {
        this.setState({
            user: record,
            visible: true,
            operationType: record.userState == 0 ? "解封" : "封号"
        });
    }
    //确定解封/封号
    operationHandleOk() {
        const { user } = this.state;
        let url = `${config.JuseMember}/userManage`
        if (user.userState == 0) {
            url += '/open'
        } else {
            url += '/close'
        }
        $.ajax({
            url,
            type: "post",
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            data: {
                id: user.id
            },
            success: res => {
                if (res.code === 200) {
                    this.getUsersList();
                    this.setState({
                        visible: false,
                    });
                }
            }
        })
    }
    //取消解封/封号
    operationHandleCancel() {
        this.setState({
            visible: false,
        });
    }
    //输入搜索关键字
    changeInkey(e) {
        this.setState({
            Inkey: e.target.value
        })
    }
    //选择搜索性别
    changeSex(value) {
        this.setState({
            sex: value
        });
    }
    //选择会员状态
    changeUserstate(value) {
        this.setState({
            userState: value
        });
    }
    //搜索
    searchUsers() {
        this.setState({
            pageindex: 1,
        }, () => {
            this.getUsersList()
        });
    }
    //重置搜索条件
    clearSearch() {
        this.setState({
            Inkey: "",
            sex: '请选择',
            userState: '请选择',
            pageindex: 1
        }, () => {
            this.getUsersList()
        });
    }
    //分页
    changePage(pageindex) {
        this.setState({
            pageindex
        }, () => {
            this.getUsersList();
        });
    }

    //查看详情
    userDetail(userData) {
        console.log('userData', userData);
        //获取会员的地址列表
        $.ajax({
            url: `${config.JuseMember}/userManage/address`,
            type: "get",
            data: {
                userId: userData.id
            },
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            success: res => {
                console.log('address', res);
                if (res.code === 200) {
                    this.setState({
                        userVisible: true,
                        userData,
                        addressList: res.data,
                    })
                } else {
                    message.error('获取会员的地址列表失败，请返回重新操作', 2);
                }
            }
        });
    }
    closeDetail() {
        this.setState({
            userVisible: false,
        })
    }

    render() {
        const columns = [{
            title: '序号',
            dataIndex: 'index',
            width: 100,
        }, {
            title: '账号',
            dataIndex: 'phone',
            width: 200,
        }, {
            title: '邮箱',
            dataIndex: 'email',
            width: 200,
        }, {
            title: '性别',
            dataIndex: 'sex',
            width: 100,
            render: text => <span>{text == "0" ? "女" : text == "1" ? "男" : text == "2" ? "保密" : ""}</span>
        }, {
            title: '注册日期',
            dataIndex: 'createdAt',
            width: 200,
            render: text => <span>{new Date(text).toLocaleString()}</span>
        }, {
            title: '最后登录时间',
            dataIndex: 'loginTime',
            width: 200,
            render: text => <span>{new Date(parseInt(text)).toLocaleString()}</span>
        }, {
            title: '状态',
            dataIndex: 'userState',
            width: 100,
            render: text => <span>{text == 0 ? "已封号" : "正常"}</span>
        }, {
            title: '查看详情',
            dataIndex: 'detail',
            width: 100,
            render: (text, record) => <a onClick={this.userDetail.bind(this, record)}>{"查看详情"}</a>
        }, {
            title: '操作',
            dataIndex: 'operation',
            width: 100,
            render: (text, record) => <a onClick={this.userOperation.bind(this, record)}>{record.userState == 0 ? "解封" : "封号"}</a>
        }];
        const { userData } = this.state;
        return (
            <div className='goods-label'>
                <div className='goods-label-cont clearfix'>
                    <div className='goods-label-cont-nav clearfix'>
                        <Breadcrumb separator=">">
                            <Breadcrumb.Item>首页</Breadcrumb.Item>
                            <Breadcrumb.Item>会员管理</Breadcrumb.Item>
                            <Breadcrumb.Item><span className='separator-a'>会员列表</span></Breadcrumb.Item>
                        </Breadcrumb>
                    </div>
                    <div className='member-content-Search clearfix'>
                        <div className='addetd addetd-z'>
                            <Input className='addetd-a-r' addonBefore="账号/邮箱" placeholder="请输入" value={this.state.Inkey} onChange={(e) => this.changeInkey(e)} />
                        </div>
                        <div className='addetd addetd-a'>
                            <InputGroup compact>
                                <Input addonBefore="性 别" />
                                <Select value={this.state.sex} onChange={this.changeSex.bind(this)}>
                                    <Option value="2">保密</Option>
                                    <Option value="1">男</Option>
                                    <Option value="0">女</Option>
                                </Select>
                            </InputGroup>
                        </div>
                        <div className='addetd addetd-a'>
                            <InputGroup compact>
                                <Input addonBefore="状 态" />
                                <Select value={this.state.userState} onChange={this.changeUserstate.bind(this)}>
                                    <Option value="1">正常</Option>
                                    <Option value="0">已封号</Option>
                                </Select>
                            </InputGroup>
                        </div>
                        <Button type="primary" className='member-button' icon="search" onClick={this.searchUsers.bind(this)}>搜索</Button>
                        <Button type="primary" className='member-button' icon="reload" onClick={this.clearSearch.bind(this)}>重置</Button>
                    </div>
                    <div className='allgoods-table clearfix'>
                        <Table
                            rowKey="id"
                            columns={columns}
                            dataSource={this.state.usersList}
                            pagination={false}
                            bordered
                        />
                    </div>
                    <div className='goods-label-let'>
                        <div className="floor-ppagi">
                            {
                                this.state.usersCount == 0 ?
                                    <p className="floor-ppagip">
                                        共{this.state.usersCount}条记录
                            </p> :
                                    <p className="floor-ppagip">
                                        当前显示
                                {this.state.pagesize * (this.state.pageindex - 1) + 1}—
                                {this.state.pagesize * this.state.pageindex < this.state.usersCount ? this.state.pagesize * this.state.pageindex : this.state.usersCount}条记录，
                                共{this.state.usersCount}条记录
                            </p>
                            }
                            <Pagination current={this.state.pageindex} total={this.state.usersCount || 1} defaultPageSize={this.state.pagesize} onChange={this.changePage.bind(this)} />
                        </div>
                    </div>
                    <div className='showmodele'>
                        <Modal title={this.state.operationType} visible={this.state.visible}
                            onCancel={this.operationHandleCancel.bind(this)}
                            width={342}
                            footer={null}
                        >
                            <p className='showp'>您确定要{this.state.operationType}吗？</p>
                            <p className='showp-a'><Button type="primary" onClick={this.operationHandleOk.bind(this)} className='member-button member-button-a'> 确 定</Button></p>
                        </Modal>
                    </div>
                    <Modal
                        title={"查看会员信息"}
                        visible={this.state.userVisible}
                        onCancel={this.closeDetail.bind(this)}
                        width={550}
                        footer={null}
                    >
                        <ul className="user-info clearfix">
                            <li style={{ width: "100%" }}>账&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;号：{userData.phone}</li>
                            <li>邮&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;箱：{userData.email}</li>
                            <li>手&nbsp;&nbsp;机&nbsp;&nbsp; 号&nbsp;&nbsp;码：{userData.phone}</li>
                            <li>性&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;别：{userData.sex == "0" ? "女" : userData.sex == "1" ? "男" : userData.sex == "2" ? "保密" : ""}</li>
                            <li>注&nbsp;&nbsp;册&nbsp;&nbsp; 日&nbsp;&nbsp;期：{new Date(userData.createdAt).toLocaleString()}</li>
                            <li>出生日期：{userData.birthday}</li>
                            <li>最后登录日期：{new Date(parseInt(userData.loginTime)).toLocaleString()}</li>
                        </ul>
                        <div className="user-address">
                            <p>收货地址：</p>
                            <ul>
                                {
                                    this.state.addressList.map((item, index) => {
                                        return (
                                            <li key={index}>
                                                {
                                                    item.isdefault == "1" && <span className="user-defaultadd">[默认]</span>
                                                }
                                                {item.area + " " + item.detail + " " + item.name + " " + item.phone}
                                            </li>
                                        )
                                    })
                                }
                            </ul>
                        </div>
                    </Modal>
                </div>
            </div>
        )
    }
}